<template>
    <div class="upload-file">
        <div class="styleDisplay" :style="{ 'justify-content': isdownload ? 'space-between' : 'flex-start' }">
            <div v-for="(fit, index) in fileList" :key="fit" class="styleDisplays"
                :style="{ 'height': isdownload ? ' 264px' : '', 'margin-right': isdownload ? '' : '20px' }">
                <el-image class="preview" :style="{ 'width': width + 'px', 'height': height + 'px' }"
                    :src="fit.url + '?x-oss-process=image/resize,w_300'" fit="fill" />
                <el-image class="delete" :src="icon_shanchu" @click="handleDelete(index)"></el-image>
                <el-image class="quanping" :style="{ 'bottom': isdownload ? '25px' : '10px' }" :src="icon_quanping"
                    @click="handlePictureCardPreview(fit)"></el-image>
                <div class="download" @click="downloads(fit)" v-if="isdownload">
                    <el-image class="downloadpic" :src="icon_xiazai"></el-image>
                    <span class="downloadtitle">下载图片</span>
                </div>
            </div>
            <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList"
                v-if="!isdownload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
                :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers"
                class="upload-file-uploader" ref="fileUploadRef" drag>
                <!-- 上传按钮 -->
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或 <em>点击上传</em>
                </div>
            </el-upload>
        </div>
        <el-upload multiple action="#" :before-upload="handleBeforeUpload" :file-list="fileList"
            v-loading.lock="isLoading" v-if="isdownload" :limit="limit" :on-error="handleUploadError"
            :on-exceed="handleExceed" :on-success="handleUploadSuccess" :http-request="httpRequest"
            :show-file-list="false" :headers="headers" class="upload-file-uploader" ref="fileUploadRef" drag>
            <!-- 上传按钮 -->
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处，或 <em>点击上传</em>
            </div>
        </el-upload>
        <!-- 上传提示 -->
        <div class="el-upload__tip" v-if="showTip">
            请上传
            <template v-if="fileSize">
                大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
            </template>
            <template v-if="fileType">
                格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
            </template>
            的文件
        </div>

        <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import { globalHeaders } from "@/utils/request";
import icon_shanchu from '@/assets/images/icon_shanchu.png'
import icon_quanping from '@/assets/images/icon_quanping.png'
import icon_xiazai from '@/assets/images/icon_xiazai.png'
import { put, getFileNameUUID } from '@/utils/oss'
const props = defineProps({
    modelValue: [String, Object, Array],
    // 数量限制
    limit: propTypes.number.def(5),
    // 大小限制(MB)
    fileSize: propTypes.number.def(5),
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
    // 是否显示提示
    isShowTip: propTypes.bool.def(true),
    // 是否展示下载按钮
    isdownload: propTypes.bool.def(true),
    // 图片宽度
    width: propTypes.number.def(320),
    // 图片高度
    height: propTypes.number.def(244),
});

const isLoading = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue']);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + "/resource/oss/upload"); // 上传文件服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);
const showTip = computed(
    () => props.isShowTip && (props.fileType || props.fileSize)
);
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const fileUploadRef = ref<ElUploadInstance>();
watch(
    () => props.modelValue,
    async (val) => {
        if (val) {
            // 首先将值转为数组
            let list: any[] = [];
            if (Array.isArray(val)) {
                list = val as any[];
            } else {
                const real_src = val.split(",");
                list = real_src.map((item: string) => import.meta.env.VITE_APP_PIC_URL + item);
            }
            // 然后将数组转为对象数组
            fileList.value = list.map((item) => {
                // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
                let itemData;
                if (typeof item === 'string') {
                    itemData = { name: item, url: item };
                } else {
                    // 此处name使用ossId 防止删除出现重名
                    itemData = { name: item.ossId, url: item.url, ossId: item.ossId };
                }
                return itemData;
            });
        } else {
            fileList.value = [];
            return [];
        }
    },
    { deep: true, immediate: true }
);
const httpRequest = (option: any) => {
    // 获取文件的后缀名
    // let objName = getFileNameUUID()
    var obj = option.file.name
    var index = obj.lastIndexOf(".");
    obj = obj.substring(index, obj.length);
    // 生成的文件名，保留文件后缀名，进行拼接      
    let objName = getFileName(option.file.name)
    const data = year + '/' + month + '/' + date
    // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
    put(`${data}/${getFileNameUUID()}/${objName}`, option.file).then(res => {
        fileList.value.push({ name: objName, url: res.url })
        emit("update:modelValue", getPicByfullPath(fileList.value));
        // proxy?.$modal.closeLoading();
        isLoading.value = false
    }).catch(error => {
        isLoading.value = false
    })
}
// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
    // 校检文件类型
    if (props.fileType.length) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
            return false;
        }
    }
    // 校检文件大小
    if (props.fileSize) {
        const isLt = file.size / 1024 / 1024 < props.fileSize;
        if (!isLt) {
            proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
            return false;
        }
    }
    isLoading.value = true
    number.value++;
    return true;
}

// 文件个数超出
const handleExceed = () => {
    proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
const handleUploadError = () => {
    proxy?.$modal.msgError("上传文件失败");
}

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
    if (res.code === 200) {
        uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId, size: (file.size / 1024 / 1024).toFixed(1) });
        uploadedSuccessfully();
    } else {
        number.value--;
        // proxy?.$modal.closeLoading();
        isLoading.value = false
        proxy?.$modal.msgError(res.msg);
        fileUploadRef.value?.handleRemove(file);
        uploadedSuccessfully();
    }
}

// 删除文件
const handleDelete = (index: number) => {
    let ossId = fileList.value[index].ossId;
    // delOss(ossId);
    fileList.value.splice(index, 1);
    emit("update:modelValue", getPicByfullPath(fileList.value));
}

// 全屏
const handleQuanping = () => {

}

// 图片全路径转成半路径
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(import.meta.env.VITE_APP_PIC_URL)[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}

// 上传结束处理
const uploadedSuccessfully = () => {
    if (number.value > 0 && uploadList.value.length === number.value) {
        fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
        uploadList.value = [];
        number.value = 0;
        emit("update:modelValue", getPicByfullPath(fileList.value));
        // proxy?.$modal.closeLoading();
        isLoading.value = false
    }
}

// 获取文件名称
const getFileName = (name: string) => {
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
    } else {
        return name;
    }
}

// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.ossId + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
// 对象转成指定字符串分隔名称
const listToStringName = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.name + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
const listToStringSize = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.size + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
// 预览
const handlePictureCardPreview = (file: any) => {
    if (isPdf(file)) {
        window.open(import.meta.env.VITE_APP_PREVIEW_URL + file.url.split(import.meta.env.VITE_APP_PIC_URL)[1], '_blank');
    } else {
        dialogImageUrl.value = file.url;
        dialogVisible.value = true;
    }
}
const isPdf = (fit: any) => {
    return fit.name.includes(".pdf")
}
/** 下载 */
const downloads = async (imgUrl: any) => {
    window.open(imgUrl.url, '_blank')
    // const urlhttps = imgUrl.url.replace('http', 'https')
    // const response = await fetch(urlhttps)
    // const blob = await response.blob()
    // // 创建下载链接
    // const url = window.URL.createObjectURL(blob)

    // const link = document.createElement('a')
    // link.href = url
    // link.download = imgUrl.name
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    // // 释放 Blob URL
    // window.URL.revokeObjectURL(url)
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
    margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
}

.upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
}

.ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
}

.styleDisplay {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
}

.styleDisplays {
    margin: 10px 0;
    position: relative;

    .preview {
        border-radius: 5px;
        border: 1px dashed #AFB6C3;
    }

    .delete {
        position: absolute;
        right: 5px;
        top: 5px;
        z-index: 5;
        width: 20px;
        height: 20px;
        cursor: pointer;
    }

    .quanping {
        position: absolute;
        right: 5px;
        z-index: 5;
        width: 20px;
        height: 20px;
        cursor: pointer;
    }

    .download {
        position: absolute;
        width: 100%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;

        .downloadpic {
            width: 14px;
            height: 14px;
        }

        .downloadtitle {
            color: #0094FF;
            font-size: 14px;
        }
    }
}
</style>